package com.ruoyi.framework.schedule;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.enums.OrderType;
import com.ruoyi.common.enums.TaskCycle;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ftp.FtpUtil;
import com.ruoyi.common.utils.seqGen.SeqGenTool;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.dataviewSystem.domain.SurveillancePicture;
import com.ruoyi.project.dataviewSystem.service.ISurveillancePictureService;
import com.ruoyi.project.orderSystem.domain.OrderStation;
import com.ruoyi.project.orderSystem.domain.TaskStation;
import com.ruoyi.project.orderSystem.domain.WorkOrder;
import com.ruoyi.project.orderSystem.domain.WorkTask;
import com.ruoyi.project.orderSystem.mapper.OrderStationMapper;
import com.ruoyi.project.orderSystem.mapper.TaskStationMapper;
import com.ruoyi.project.orderSystem.mapper.WorkOrderMapper;
import com.ruoyi.project.orderSystem.service.IWorkOrderService;
import com.ruoyi.project.orderSystem.service.IWorkTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@EnableScheduling
public class TaskSchedule {
    private final Logger logger = LoggerFactory.getLogger(Object.class);
    @Autowired
    private IWorkTaskService iWorkTaskService;
    @Autowired
    private IWorkOrderService iWorkOrderService;
    @Autowired
    private WorkOrderMapper workOrderMapper;
    @Autowired
    private TaskStationMapper taskStationMapper;
    @Autowired
    private OrderStationMapper orderStationMapper;
    @Autowired
    private ISurveillancePictureService iSurveillancePictureService;
    private final static  SimpleDateFormat daySf = new SimpleDateFormat("yyyy-MM-dd");
    private final static  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private final static SimpleDateFormat allsdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");


    @Async("asyncServiceExecutor")
    @Scheduled(cron ="0 0/1 * * * ?" )
    public void dailyTaskGenerator(){
        //查询周工单
        List<WorkTask> workTasks = iWorkTaskService.getWorkTaskListOntime();

        for (Iterator<WorkTask> iterator = workTasks.iterator();iterator.hasNext();){
            WorkTask workTask = iterator.next();

            Date startDate =null;
            Date shouldGenerateDay = null;
            //获取最后生成的工单
            WorkOrder lastWorkOrder = iWorkOrderService.selectLastOnWorkOrderByTaskId(workTask.getId());
            if(lastWorkOrder!=null){
            int cycleNum = workTask.getCycleNum();
            Date gmtRequireStart = lastWorkOrder.getGmtRequireStart();
                if(TaskCycle.TASK_DAY.equals(TaskCycle.getTaskCycle(workTask.getTaskCycle()))){
                    //周期时间转换
                    shouldGenerateDay = DateUtils.addDays(gmtRequireStart, cycleNum);
                }else if(TaskCycle.TASK_WEEK.equals(TaskCycle.getTaskCycle(workTask.getTaskCycle()))) {
                    shouldGenerateDay = DateUtils.addWeeks(gmtRequireStart, cycleNum);

                }else if(TaskCycle.TASK_MONTH.equals(TaskCycle.getTaskCycle(workTask.getTaskCycle()))){
                    shouldGenerateDay = DateUtils.addMonths(gmtRequireStart, cycleNum);
                }else {
                    iterator.remove();
                    continue;
                }
                if(shouldGenerateDay.after(new Date())){
                    //未到期
                    iterator.remove();
                }else {
                    this.generatorWorkOrder(workTask,new Date());
                }
            }else {
                //直接生成新的工单
                this.generatorWorkOrder(workTask,new Date());
            }
        }
        System.out.println("kkkk======");
    }

    private int generatorWorkOrder(WorkTask workTask,Date startTime){
        try {
            //获取任务对应的厂站
            List<TaskStation> taskStationList = taskStationMapper.selectTaskStationByTaskId(workTask.getId());
            if(taskStationList.size()==0){
                logger.error("该任务没有选择站点，不生成工单");
                return 0;
            }
            //生成工单号
            String prefix ="";
            if(OrderType.INSPECT_ORDER.equals(OrderType.getOrderType(workTask.getOrderType()))){
                prefix ="XJDD";
            }else if(OrderType.MAINTAIN_ORDER.equals(OrderType.getOrderType(workTask.getOrderType()))) {
                prefix ="BYDD";
            }else if(OrderType.UPHOLD_ORDER.equals(OrderType.getOrderType(workTask.getOrderType()))) {
                prefix ="WHDD";
            }else if(OrderType.REPAIR_ORDER.equals(OrderType.getOrderType(workTask.getOrderType()))) {
                prefix ="WXDD";
            }
            //生成工单
            WorkOrder workOrder = new WorkOrder();
            workOrder.setOrderSn(prefix+ SeqGenTool.seq());
            workOrder.setOrderType(OrderType.getOrderType(workTask.getOrderType()).getKey());
            workOrder.setIsSeed(1);
            workOrder.setExecutorIds(workTask.getExecutorIds());
            workOrder.setOrderTitle("日常"+OrderType.getOrderType(workOrder.getOrderType()).getOrderType());
            workOrder.setOrderDescription(workTask.getTaskName()+DateUtils.date2Str(new Date(),DateUtils.YYYY_MM_DD));
            workOrder.setSeedUser(1L);
            workOrder.setGmtRequireStart(startTime);
            workOrder.setGmtRequireEnd(DateUtils.addDays(startTime,7));
            workOrder.setCreator(1L);
            workOrder.setTaskId(workTask.getId());
            workOrder.setGmtCreate(new Date());
            int i = workOrderMapper.insertWorkOrder(workOrder);

                List<OrderStation> orderStations = new ArrayList<>();
            taskStationList.forEach(x->{
                    OrderStation orderStation = new OrderStation();
                    orderStation.setStationId(x.getStationId());
                    orderStation.setOrderId(workOrder.getId());
                    orderStations.add(orderStation);
                });
                orderStationMapper.batchInsert(orderStations);
            return i;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("定时任务生成工单异常"+"任务编号"+workTask.getTaskSn());
        }
        return 0;
    }

    @Async("asyncServiceExecutor")
    @Scheduled(cron ="0 0/5 * * * ?" )
    public void getPicFromFtp(){

        String surveillancePicPath = RuoYiConfig.getSurveillancePicPath();
        String remoteAddr = "121.37.31.192";
        String userName = "root";
        String pswd = "We@#Hx87775236@#!!!";
        ArrayList<String> linuxFileList = new ArrayList<>();
        try {
            linuxFileList = FtpUtil.getLinuxFileList(RuoYiConfig.getSurveillancePicPath(), remoteAddr, userName, pswd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(linuxFileList.size()==0){
            return;
        }
        List<String> existsUrls = iSurveillancePictureService.getAllPicUrl(new SurveillancePicture());
//        List<String> collect1 = surveillancePictures.stream().map(SurveillancePicture::getUrl).collect(Collectors.toList());
        List<SurveillancePicture> collect = linuxFileList.stream().map(x -> {
            if(x.startsWith("LDKS")){
                String[] s = x.split("_");
                String str = s[2];
                Date date = null;
                try {
                    date = allsdf.parse(str);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if (daySf.format(date).equals(daySf.format(new Date()))) {
                    String z = Constants.FTP_PREFIX + "/" + x;
                    boolean contains = existsUrls.contains(z);
                    if(!contains){
                        SurveillancePicture surveillancePicture = new SurveillancePicture();
                        surveillancePicture.setGmtCreate(new Date());
                        surveillancePicture.setGmtUpload(date);
                        surveillancePicture.setPictureType(1);
                        surveillancePicture.setStationcode(s[0]);
                        surveillancePicture.setUrl(z);
//                surveillancePicture.setU
                        return surveillancePicture;
                    }
                }
            }
                return null;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        if(collect.size()>0){
            System.out.println("kkkk");
            int i =iSurveillancePictureService.batchInsert(collect);
        }
    }
}
